/*
 * @Author: luthor luthor-li@qq.com
 * @Date: 2024-10-27 23:22:16
 * @LastEditors: luthor luthor-li@qq.com
 * @LastEditTime: 2024-10-27 23:22:24
 * @FilePath: \tilesethub_back\controllers\tileController.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const User = require('../models/user')
const { verifyToken } = require('../services/tokenService')
const fs = require('fs')
const path = require('path')

const getTileset = async ctx => {
  const { filepath } = ctx.params
  const token = ctx.headers['f-token'] // 自定义头部 f-token
  if (!token) {
    ctx.status = 401
    ctx.body = { message: 'Unauthorized: Token required' }
    return
  }

  try {
    const decoded = verifyToken(token)
    const user = await User.findOne({ id: decoded.id, key: decoded.key })
    if (!user) {
      ctx.status = 401
      ctx.body = { message: 'Unauthorized' }
      return
    }

    const tilesetName = filepath.split('/')[0]
    if (!user.allowedTilesets.includes(tilesetName)) {
      ctx.status = 403
      ctx.body = { message: 'Access denied' }
      return
    }

    const filePath = path.join(__dirname, '../static/tilesets', filepath)
    if (fs.existsSync(filePath)) {
      ctx.body = fs.createReadStream(filePath)
    } else {
      ctx.status = 404
      ctx.body = { message: 'File not found' }
    }
  } catch (error) {
    ctx.status = 401
    ctx.body = { message: 'Invalid token' }
  }
}

module.exports = { getTileset }
